<template>
  <span
    v-if="type === 'text'"
    :style="textDictStyle()"
    @click="emits('clickDictItem', dict)"
  >
    {{ dict.label }}
  </span>
  <n-tag
    v-else-if="type === 'tag'"
    v-bind="tagProps"
    :type="dict.listClass || 'primary'"
    @click="emits('clickDictItem', dict)"
  >
    {{ dict.label }}
  </n-tag>
</template>

<script setup lang="ts" name="ProDict">
  import { TagProps } from 'naive-ui'
  import { Dict } from './type'

  type PropsType = {
    value: number | string | boolean
    type?: 'text' | 'tag'
    dictCode?: string | number
    dictOptions?: Dict[]
    labelCode?: string
    valueCode?: string
    tagProps?: TagProps
  }

  const props = withDefaults(defineProps<PropsType>(), {
    type: 'text',
    labelCode: 'label',
    valueCode: 'value'
  })

  const emits = defineEmits(['clickDictItem'])

  const dictOptions =
    props.dictOptions ||
    (props.dictCode && useDictData(props.dictCode).value) ||
    []

  const findDictItem = (
    data: any[],
    value: string | number | boolean,
    valueCode = 'value'
  ) => {
    const findItem = data?.find((item) => item[valueCode] == value) as Dict
    return findItem || {}
  }

  const dict = computed(() => {
    return findDictItem(dictOptions, props.value)
  })

  const DICT_COLOR_STYLE = {
    success: 'color: #37a05b',
    primary: 'color: #3080ed',
    warning: 'color: #eba134',
    error: 'color: #c93252',
    info: 'color: #777c82'
  }

  const textDictStyle = () => {
    const { cssClass, listClass } = dict.value
    if (cssClass) return cssClass
    else if (listClass) {
      return DICT_COLOR_STYLE[listClass]
    }
  }
</script>

<style lang="less" scoped></style>
